package com.lanxin.xxform.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lanxin.xxform.aspects.exceptions.ParamException;
import com.lanxin.xxform.aspects.exceptions.ServiceException;
import com.lanxin.xxform.beans.User;
import com.lanxin.xxform.services.UserService;
import com.lanxin.xxform.tools.JsonResult;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param account
     * @param password
     * @param request
     * @return
     */
    @PostMapping("register.do")
    public JsonResult register(
        @RequestParam(required = true) String account,
        @RequestParam(required = true) String password,
        HttpServletRequest request
    ) {
        if (account.isEmpty()) {
            throw new ParamException("请填写账户名称");
        }
        return new JsonResult(userService.register(account.trim(), password.trim(), request.getRemoteAddr()));
    }

    /**
     * 登录
     * @param account
     * @param password
     * @param request
     * @return
     */
    @PostMapping("login.do")
    public JsonResult login(
        @RequestParam(required = true) String account,
        @RequestParam(required = true) String password,
        HttpServletRequest request
    ) {
        User user = userService.login(account, password, request.getRemoteAddr());
        if (user == null) {
            throw new ServiceException("登录失败");
        }
        HttpSession session = request.getSession();
        session.setAttribute("uid", user.getId());
        if (user.getName().isEmpty()) {
            session.setAttribute("name", user.getAccount());
        } else {
            session.setAttribute("name", user.getName());
        }
        return new JsonResult();
    }

    @PostMapping("logout.do")
    public JsonResult logout(HttpSession session) {
        session.removeAttribute("uid");
        session.removeAttribute("name");
        return new JsonResult();
    }
}
